<template>
	<div class="w-[366px] bg-bg-8 rounded-lg px-5">
		<div class="h-[108px] flex justify-center">
			<div class="w-[108px] h-full bg-bg-3 -translate-y-5 rounded-md relative">
				<base-image
					:src="imgSrc"
					default="placeholder.svg"
					:type="imgServer"
					@onload="loaded = true"
					class="w-full h-full object-cover rounded-md" />
				<base-icon
					v-if="loaded"
					class="text-[22px] absolute top-1 right-1 text-white"
					:name="iconName"
					@click.stop="handleCollect" />
				<!-- <img
					v-if="1"
					class="w-[24px] h-[24px] absolute top-1 right-1"
					@click.stop="handleCollect"
					:src="GameCollect" />
				<img
					@click.stop="handleCollect"
					v-else
					class="w-[24px] h-[24px] absolute top-1 right-1"
					:src="GameCollected" /> -->
			</div>
		</div>
		<div class="-translate-y-3">
			<div class="text-t-1 app-font-bold text-lg text-center">
				{{ data?.gameName }}
			</div>
			<div class="text-t-3 app-font-bold text-sm text-center pb-2">
				{{ data?.portalDisplayName || data?.providerName }}
			</div>
			<div v-if="type === 'slots'" class="pb-3 mt-2">
				<div class="flex flex-col text-sm items-center px-4 rounded-lg bg-bg-3">
					<div class="leader pt-[2px] w-[204px] text-center h-[22px] translate-y-[-10px]">
						<span class="">{{ $t('slotsDetail.title') }}</span>
					</div>
					<div
						class="flex top translate-y-[-5px] h-8 items-center"
						v-if="!data?.rankingFirst?.userId">
						<span class="empty">{{ $t('slotspre.vacant') }}</span>
						<base-icon
							@click.stop="showTopThree = true"
							class="ml-1"
							:name="'expandarrow'"
							:size="24"
							:color="'var(--color-bg-10)'" />
					</div>
					<div
						v-else
						class="flex items-center translate-y-[-6px] cursor-pointer"
						@click="handleShowProfile(data?.rankingFirst)">
						<account-avatar
							:data="data?.rankingFirst?.avatar"
							:userId="data?.rankingFirst?.userId"
							:width="34"></account-avatar>
						<account-vip class="ml-1" :level="data?.rankingFirst?.vip || 0"></account-vip>
						<div class="flex-1 min-w-0">
							<div class="w-full py-[1px] overflow-hidden text-ellipsis whitespace-nowrap text-t-1">
								{{ data?.rankingFirst?.nickName || data?.rankingFirst?.userName }}
							</div>
							<div class="w-full overflow-hidden text-ellipsis whitespace-nowrap text-success">
								<up-amount-slot :value="data?.rankingFirst?.payout || 0" />
							</div>
						</div>
						<base-icon
							@click.stop="showTopThree = true"
							class="ml-1"
							:name="'expandarrow'"
							:size="24"
							:color="'var(--color-bg-10)'" />
					</div>
					<div
						class="border-t-[1px] py-2 text-t-3 text-xs w-full border-border-1 flex items-center justify-around">
						<div class="column">
							<div>{{ $t('slotsDetail.myRank') }}</div>
							<div class="rank text-center text-t-1">
								{{
									accountStore.isLogin && data?.myUser?.payout > 0
										? data?.myUser?.order && data?.myUser?.order <= 100
											? data?.myUser.order
											: '100+'
										: '-'
								}}
							</div>
						</div>
						<div class="column">
							<div>{{ $t('slotsDetail.myPayout') }}</div>
							<div class="text-center">
								<up-amount-slot
									v-if="accountStore.isLogin"
									class="text-success"
									:value="data?.myUser?.payout || 0" />
								<span v-else>-</span>
							</div>
						</div>
					</div>
				</div>
			</div>
			<div class="py-2 flex justify-around">
				<base-button
					v-if="type !== 'casino' && data?.providerName === 'Pragmatic Play'"
					@click="handleDemo"
					:loading="loadingDemo"
					:block="false"
					type="warning"
					:disabled="!data?.gameName"
					class="ml-2 w-[120px]"
					textT="slotspre.demo"></base-button>
				<base-button
					@click="handlePlay"
					:loading="loading"
					:disabled="!data?.gameName || gameError"
					class="ml-2 w-[120px]"
					:block="false"
					type="primary"
					textT="slotspre.play"></base-button>
			</div>
		</div>
		<base-popup-small
			v-if="
				type === 'slots' && data?.lastWeekGameMaxTop3List && data?.lastWeekGameMaxTop3List.length
			"
			v-model:show="showTopThree"
			@close="showTopThree = false"
			title=" ">
			<TopThree
				:lastRankFirst="data?.lastWeekRankingFirst"
				:lastTopThree="data?.lastWeekGameMaxTop3List" />
		</base-popup-small>
	</div>
</template>
<script lang="ts" setup>
import { computed, ref } from 'vue'
import { BaseButton, BaseImage, BaseIcon, BasePopupSmall } from '@/components/base'
import { useAccountStore, useProfileStore, useWalletStore } from '@/store'
//import { casinoGoinGame } from '@/api/casino'
import { goinGame } from '@/api/slots'
import { launchGameAPI, getGameDetailBySlug } from '@/api/other.ts'
import { useRoute } from 'vue-router'
import { UpAmountSlot, UpSwitchTabsEnum } from '@/components/up'
import AccountVip from '@/components/account/account-vip/index.vue'
import AccountAvatar from '@/components/account/account-avatar/index.vue'
import TopThree from '../dialog/top-three.vue'
//import GameCollected from '@/assets/img/slots/collected.png'

const accountStore = useAccountStore()
const route = useRoute()
const profileStore = useProfileStore()
const walletStore = useWalletStore()

const loading = ref(false)
const loadingDemo = ref(false)
const showTopThree = ref(false)
const loaded = ref(false)
const gameError = ref(false)
const emit = defineEmits(['loaded', 'collect'])
const props = defineProps({
	type: {
		type: String,
		default: 'slots'
	},
	data: {
		type: Object as any,
		default: () => {}
	},
	firstLoad: {
		type: Boolean,
		default: false
	},
	backUrl: {
		type: String,
		default: ''
	}
})

const iconName = computed(() => {
	if (props.data?.collectState || props.data?.favoriteState) {
		return 'love-filled'
	}
	return 'love'
})

const imgSrc = computed(() => {
	if (props.data?.gameIcon) {
		return props.data?.gameIcon
	}
	if (props.data?.icon) {
		return props.data?.icon
	}
	return 'placeholder.svg'
})

const imgServer = computed(() => {
	if (imgSrc.value.indexOf('http') === 0) {
		return 'network'
	}
	if (imgSrc.value !== 'placeholder.svg') {
		return 'server'
	}
	return 'local'
})

const handleCollect = () => {
	if (accountStore.isLogin) {
		emit('collect')
	} else {
		accountStore.showLogin()
	}
}

const handleShowProfile = (val: any) => {
	profileStore.showProfile({
		show: true,
		userId: val.userId,
		tab: UpSwitchTabsEnum.slots
	})
}

const handleDemo = async () => {
	if (accountStore.isLogin) {
		loadingDemo.value = true
		try {
			const res = await goinGame(props.data?.id, {
				lobbyUrl: props.backUrl,
				isTest: true
			})
			const { type, content } = res.data
			switch (type) {
				case 'HTML':
					emit('loaded', {
						type: 'HTML',
						url: content,
						isPlay: false
					})
					break
				case 'URL':
					emit('loaded', {
						type: 'URL',
						url: content,
						isPlay: false
					})
					break
			}
		} catch (e: any) {
			if (e.code === 201) {
				emit('loaded', {
					type: 'error',
					url: 'region',
					isPlay: false
				})
			} else {
				emit('loaded', {
					type: 'error',
					url: 'maintain',
					isPlay: false
				})
			}
		}
		loadingDemo.value = false
	} else {
		accountStore.showLogin()
	}
}

const handlePlay = async (isFirst = false) => {
	if (accountStore.isLogin) {
		if (props.firstLoad) {
			emit('loaded', {
				type: 'HIDE'
			})
			return
		}
		if (typeof isFirst !== 'boolean') {
			loading.value = true
		}
		if (props.type === 'casino') {
			try {
				const result = (await getGameDetailBySlug({
					slug: route.params.id
				})) as any
				const { data, code } = (await launchGameAPI({
					gameCode: result.data.gameCode,
					walletCurrency: walletStore.balanceCur?.currency,
					gameCurrency: 'USD',
					device: 'DESKTOP',
					funMode: false
				})) as any
				// const { data, code } = await casinoGoinGame({
				// 	backUrl: props.backUrl,
				// 	bindName: route.params.id
				// })
				if (code === 200) {
					emit('loaded', {
						type: 'URL',
						url: data?.game_url,
						isPlay: true,
						isFirst: typeof isFirst === 'boolean'
					})
					// window.open(data?.url, '_blank')
					gameError.value = false
				} else {
					gameError.value = true
					emit('loaded', {
						type: 'errors',
						url: 'maintain',
						isPlay: false,
						isFirst: typeof isFirst === 'boolean'
					})
				}
			} catch (e: any) {
				gameError.value = true
				emit('loaded', {
					type: 'error',
					url: 'maintain',
					isPlay: false,
					isFirst: typeof isFirst === 'boolean'
				})
			}
		} else {
			try {
				console.log('======', props.data)
				const res = await goinGame(props.data?.id, {
					lobbyUrl: props.backUrl,
					isTest: false
				})
				const { type, content } = res.data
				switch (type) {
					case 'HTML':
						emit('loaded', {
							type: 'HTML',
							url: content,
							isPlay: true,
							isFirst: typeof isFirst === 'boolean'
						})
						break
					case 'URL':
						emit('loaded', {
							type: 'URL',
							url: content,
							isPlay: true,
							isFirst: typeof isFirst === 'boolean'
						})
						break
				}
				gameError.value = false
			} catch (e: any) {
				gameError.value = true
				if (e.code === 409) {
					emit('loaded', {
						type: 'error',
						url: 'region',
						isPlay: false,
						isFirst: typeof isFirst === 'boolean'
					})
				} else {
					emit('loaded', {
						type: 'error',
						url: 'maintain',
						isPlay: false,
						isFirst: typeof isFirst === 'boolean'
					})
				}
			}
		}
		loading.value = false
	} else {
		accountStore.showLogin()
	}
}

defineExpose({
	handleDemo,
	handlePlay
})
</script>
<style lang="scss" scoped>
.leader {
	background-image: url('@/assets/img/slots/gameDetailTitleBg.svg');
	background-size: contain;
	background-repeat: no-repeat;
}
</style>
